import {message, Button, Divider, Popconfirm, Select, notification} from 'antd'
import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, history } from 'umi'
import { querySocialSecurityPlansPage, addSecurityPlan, delSecurityPlan } from '../service'
import CreateForm from './components/CreateForm'
import CreatePersonChangeTable from '../../components/CreateTable'
import moment from 'moment'
import CreatePersonForm from '@/pages/Security/SocialSecurityPlan/List/components/CreatePersonForm'
import { getCompanyListAuth } from '@/pages/Security/service'

const { Option } = Select

const TableList = (props) => {
  const { currentUser } = props
  const { authorities } = currentUser
  const actionRef = useRef()
  const formRef = useRef()
  const [securityType] = useState(0)
  const [done, setDone] = useState(false)
  const [visible, setVisible] = useState(false)
  const [personFormVisible, setPersonFormVisible] = useState(false)
  const [current, setCurrent] = useState(undefined)
  const [loading, setLoading] = useState(false)
  const [personChangeVisible, setPersonChangeVisible] = useState(false)
  const [contractData, setContractData] = useState(null)

  useEffect(() => {
    getCompanyListAuth().then(res => {
      if(res.flag){
        res && setContractData(res.data)
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
    })
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'promotionId',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    /*{
      title: '社保方案名称',
      dataIndex: 'securityName',
    },*/
    {
      title: '参保地',
      dataIndex: 'cityName',
    },
    {
      title: '参保单位',
      dataIndex: 'unitName',
      renderFormItem: (item, props) => {
        return <Select placeholder="请选择参保单位" showSearch allowClear
                       filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
          {contractData.length > 0 ? contractData.map((item, index) => {
            return (
              <Option value={item.name} key={index} lable={item}>
                {item.name}
              </Option>
            )
          }) : ''}
        </Select>
      },
    },
    {
      title: '参保人数',
      dataIndex: 'number',
      hideInSearch: true,
    },
    {
      title: '方案汇缴期',
      dataIndex: 'remittancePeriod',
      hideInSearch: true,
      render: (text) => moment(new Date()).format('YYYY-MM')
    },
    {
      title: '汇缴确认状态',
      dataIndex: 'confirmStatus',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      render: (item, record) => (
        <>
          {<a onClick={() => updatePlan(record)}>编辑方案</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => setPlanPerson(record)}>配置人员</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showPersonChange(record)}>查看人员变动</a>}
          {
            authorities.indexOf('emp:security:delete') > -1 &&
            <>
              <Divider type="vertical"/>
              <Popconfirm title="是否要删除此方案？" cancelText='取消' okText='确认' onConfirm={(e) => deletePlan(record)}>
                <a>删除</a>
              </Popconfirm>
            </>
          }
        </>
      ),
    },
  ]

  const handleCancel = () => {
    setCurrent(null)
    setVisible(false)
  }

  const personHandleCancel = () => {
    setCurrent(null)
    setPersonFormVisible(false)
  }

  const personChangeHandleCancel = () => {
    setCurrent(null)
    setPersonChangeVisible(false)
  }

  const addPlan = () => {
    setVisible(true)
    setCurrent(null)
  }

  const exportPlan = () => {
    let searchData = formRef.current.getFieldsValue()
    let { unitName, cityName } = searchData
    let url = '/hr-ssc/api/api-admin/export/ExportSecurityList?flag=1'
    if (unitName)
      url = url + '&unitName=' + unitName
    if (cityName)
      url = url + '&cityName=' + cityName
    window.open(url)
  }

  const updatePlan = (record) => {
    setVisible(true)
    setCurrent(record)
  }

  const setPlanPerson = (record) => {
    setPersonFormVisible(true)
    setCurrent(record)
  }

  const showPersonChange = (record) => {
    setCurrent(record)
    setPersonChangeVisible(true)
  }

  const deletePlan = (record) => {
    delSecurityPlan(record).then(res => {
      if (res.flag) {
        message.success('删除社保方案成功！')
      } else {
        message.error(res.error)
      }
      actionRef.current.reload()
    })
  }

  const handleSubmit = (values) => {
    setDone(false)
    setCurrent(null)
    setVisible(false)
    values.type = securityType
    addSecurityPlan(values).then((req) => {
      if (req.flag) {
        message.success('社保方案信息保存成功！')
      } else {
        message.error(`操作保存失败！${req.error}`)
      }
      actionRef.current.reload()
    })
  }

  return (
    <PageHeaderWrapper>
      {
        contractData && <ProTable
          actionRef={actionRef}
          formRef={formRef}
          loading={loading}
          rowKey="securityId"
          request={(params) => querySocialSecurityPlansPage(params, securityType)}
          columns={columns}
          toolBarRender={(action, { selectedRows }) => [
            <Button key='button' type="primary" onClick={() => addPlan()}>新建</Button>,
            <Button key='export' type="primary" onClick={() => exportPlan()}>导出</Button>,
          ]}
        />
      }

      <CreateForm
        type={securityType}
        done={done}
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <CreatePersonForm
        type={securityType}
        done={done}
        current={current}
        visible={personFormVisible}
        onCancel={personHandleCancel}
      />
      <CreatePersonChangeTable
        current={current}
        visible={personChangeVisible}
        type={'social'}
        onCancel={personChangeHandleCancel}
      />
    </PageHeaderWrapper>
  )
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(TableList)
